/**
 * Created by charsen on 16/5/25.
 */
directives.directive('newPage', ["$rootScope", "tools", "$timeout", "$location", function ($rootScope, tools, $timeout, $location) {
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        link: function (scope, element, attr) {
            scope.pageName = "";
            scope.errInfo = "";
            scope.tables = [];
            scope.allFiles = {};
            scope.allTables = {};
            scope.dataSources = [];
            scope.tableType = '';
            scope.curr_source = null;
            scope.curr_tablle = null;
            scope.errInfoShown = false;

            scope.from_data_manager = false;
            scope.tableId_from_data_manager = "";
            scope.tableDesc_from_data_manager = "";
            scope.tableType_from_data_manager = "";

            scope.tableType = "数据库源数据";

            var file_mode = false;
            var finished_call_back = null;

            $(element).find('.dropdown.categoryList').dropdown({});

            $rootScope.$on('NEW_PAGE_EV', function (e, cb) {
                scope.pageName = "";
                scope.errInfo = "";
                scope.tables = [];
                scope.allFiles = {};
                scope.allTables = {};
                scope.dataSources = [];
                scope.tableType = '';
                scope.curr_source = null;
                scope.curr_tablle = null;
                scope.errInfoShown = false;

                scope.tableType = "数据库源数据";

                file_mode = false;
                $(element).modal('show');
                getDataSources();

                if (cb) {
                    finished_call_back = cb;
                }
            });

            scope.toDbManager = function () {
                scope.close();
                $location.url('/dbManager');
            }

            // 获取数据源
            function getDataSources () {
                tools.get({
                    url: '/Ibm-Client/getLoginUserInfo.htm',
                    data: {},
                    succ: function (resp) {
                        if (resp.success) {
                            for (var i in resp.value.dataSources) {
                                scope.dataSources.push(resp.value.dataSources[i]);
                            }

                            $(element).find('.dropdown.sourceList').dropdown({});

                            scope.tableType = '数据库源数据';

                            // 切换到第一个源
                            scope.switctSource(scope.dataSources[0]);
                        }
                    }
                });
            };

            // 切换数据源
            scope.switctSource = function (source) {
                tools.get({
                    url: '/Ibm-Client/changeDataSource.htm',
                    data: {
                        sourceId: source.sourceId
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.curr_source = source;

                            // 默认使用数据库源数据
                            getIbmTables(source.sourceId, 'table', function () {
                                scope.switchTables('IbmTables');
                            });

                            getFileTables(source.sourceId);
                            getIbmAggregateFunctions(source.sourceId);
                            getIbmMultiRelationTables(source.sourceId);
                            getIbmRelationTables(source.sourceId, 'type');
                        }
                    }
                });
            }

            // 切换表种类
            scope.switchTables = function (type) {
                $timeout(function () {
                    scope.tableType = type;
                    scope.tables = scope.allTables[type];
                    scope.curr_tablle = scope.tables[0];
                }, 0);

                $timeout(function () {
                    $(element).find('.dropdown.tableList').dropdown();

                    switch (type) {
                        case 'IbmTables':
                            scope.tableType = '数据库源数据';
                            break;

                        case 'RelationTables':
                            scope.tableType = '关联关系数据';
                            break;

                        case 'multiRelationTables':
                            scope.tableType = '多关联关系数据';
                            break;

                        case 'IbmAggregateFunctions':
                            scope.tableType = '分类汇总数据';
                            break;

                        case 'FileTables':
                            scope.tableType = '上传文件数据';
                            break;
                    }
                }, 50);

                if (type == 'FileTables') {
                    file_mode = true;
                } else {
                    file_mode = false;
                }
            }

            // 切换表
            scope.switchTable = function (index) {
                scope.curr_tablle = scope.tables[index];
            }

            // 获取基础表
            function getIbmTables (dataSourceId, type, cb) {
                tools.get({
                    url: '/Ibm-Client/getIbmTables.htm',
                    data: {
                        dataSourceId: dataSourceId,
                        type: type
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.allTables['IbmTables'] = resp.value;
                            cb && cb();
                        }
                    }
                });
            }

            // 获取关联表
            function getIbmRelationTables (dataSourceId, type) {
                tools.get({
                    url: '/Ibm-Client/getIbmRelationTables.htm',
                    data: {
                        dataSourceId: dataSourceId,
                        type: type
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.allTables['RelationTables'] = resp.value;
                        }
                    }
                });
            }

            // 获取汇总表
            function getIbmAggregateFunctions (dataSourceId) {
                tools.get({
                    url: '/Ibm-Client/getIbmAggregateFunctions.htm',
                    data: {
                        dataSourceId: dataSourceId
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.allTables['IbmAggregateFunctions'] = resp.value;
                        }
                    }
                });
            }

            // 获取多表关联数据
            function getIbmMultiRelationTables (dataSourceId) {
                tools.get({
                    url: '/Ibm-Client/getMultiRelationTables.htm',
                    data: {
                        dataSourceId: dataSourceId
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.allTables['multiRelationTables'] = resp.value;
                        }
                    }
                });
            }

            // 获取文件表
            function getFileTables (dataSourceId) {
                tools.get({
                    url: '/Ibm-Client/getFileTables.htm',
                    data: {
                        dataSourceId: dataSourceId
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.allTables['FileTables'] = [];

                            angular.forEach(resp.value, function (file) {
                                if (file.tableDesc) {
                                    scope.allTables['FileTables'].push(file);
                                }
                            });
                        }
                    }
                });
            }

            scope.close = function () {
                $(element).modal('hide');
            }

            scope.ok = function () {
                scope.pageName = tools.trim(scope.pageName);

                if (!scope.pageName) {
                    scope.errInfoShown = true;
                    scope.errInfo = "新报表名称不能为空!";
                    return;
                } else if (!scope.curr_tablle && !scope.from_data_manager) {
                    scope.errInfoShown = true;
                    scope.errInfo = "请选择一个新报表所使用的数据表!";
                    return;
                }

                tools.get({
                    url: '/Ibm-Client/updatePage.htm',
                    data: {
                        chartStyle: 'default',
                        pageName: scope.pageName,
                        tbId: scope.from_data_manager ? scope.tableId_from_data_manager : scope.curr_tablle.tbId,
                        tableType: scope.from_data_manager ? scope.tableType_from_data_manager : scope.curr_tablle.tableType,
                        pageJson: "{'jsonObject':" + JSON.stringify({
                            core: {
                                charts: [],
                                sheets: [],
                                objects: {
                                    text: [],
                                    images: []
                                },
                                conditions: {}
                            }
                        }) + '}'
                    },
                    succ: function (resp) {
                        if (resp.success) {
                            scope.close();
                            $location.url('/editor?id=' + resp.value + '&tbId=' + (scope.from_data_manager ? scope.tableId_from_data_manager : scope.curr_tablle.tbId) + '&tableType=' + (scope.from_data_manager ? scope.tableType_from_data_manager : scope.curr_tablle.tableType) + '&sharerName=userself');

                            scope.from_data_manager = false;
                            scope.tableId_from_data_manager = "";
                            scope.tableDesc_from_data_manager = "";
                            scope.tableType_from_data_manager = "";

                            finished_call_back(resp.value);
                        }
                    }
                });
            }

            $rootScope.$on('NEW_PAGE_FROM_DATA_MANAGER', function (e, config) {
                scope.from_data_manager = true;

                scope.tableId_from_data_manager = config.tbId;
                scope.tableDesc_from_data_manager = config.tableDesc;
                scope.tableType_from_data_manager = config.tableType;

                $(element).modal('show');
                getDataSources();
            });
        },
        templateUrl: "/trend-new-BI/app/components/common/newPage/newPageView.html"
    }
}]);